import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi, getProfile } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const showLoginDialog = ref(false)

  // 设置Token
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken) // 保存到 localStorage
  }

  // 清除Token
  const removeToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
  }

  // 登录
  const login = async (loginForm) => {
    try {
      const tokenData = await loginApi(loginForm)
      setToken(tokenData)
      return true
    } catch (error) {
      console.error('登录失败:', error)
      return false
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const info = await getProfile()
      setUserInfo(info)
      return info
    } catch (error) {
      console.error('获取用户信息失败:', error)
      return null
    }
  }

  // 退出登录
  const logout = () => {
    removeToken()
    clearUserInfo()
  }

  // 检查是否登录
  const isLoggedIn = () => {
    return !!token.value
  }

  // 打开登录对话框
  const openLoginDialog = () => {
    showLoginDialog.value = true
  }

  // 关闭登录对话框
  const closeLoginDialog = () => {
    showLoginDialog.value = false
  }

  return {
    token,
    userInfo,
    showLoginDialog,
    setToken,
    removeToken,
    setUserInfo,
    clearUserInfo,
    login,
    getUserInfo,
    logout,
    isLoggedIn,
    openLoginDialog,
    closeLoginDialog
  }
})
